package co.pushmall.modules.shop.rest;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.pushmall.aop.log.Log;
import co.pushmall.constant.ShopConstants;
import co.pushmall.modules.shop.domain.PushMallStoreProduct;
import co.pushmall.modules.shop.service.PushMallStoreProductService;
import co.pushmall.modules.shop.service.dto.PushMallStoreProductDTO;
import co.pushmall.modules.shop.service.dto.PushMallStoreProductQueryCriteria;
import co.pushmall.utils.OrderUtil;
import co.pushmall.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author pushmall
 * @date 2019-10-04
 */
@Api(tags = "商城:商品管理")
@RestController
@RequestMapping("api")
public class StoreProductController {

    private final PushMallStoreProductService pushMallStoreProductService;

    public StoreProductController(PushMallStoreProductService pushMallStoreProductService) {
        this.pushMallStoreProductService = pushMallStoreProductService;
    }

    private Map<String, Object> getPushMallStoreProductList(PushMallStoreProductQueryCriteria criteria, Pageable pageable) {
        return pushMallStoreProductService.queryAll(criteria, pageable);
    }

    @Log("查询商品")
    @ApiOperation(value = "查询商品")
    @GetMapping(value = "/PmStoreProduct")
    @PreAuthorize("@el.check('admin','YXSTOREPRODUCT_ALL','YXSTOREPRODUCT_SELECT')")
    public ResponseEntity getPushMallStoreProducts(PushMallStoreProductQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity(getPushMallStoreProductList(criteria, pageable), HttpStatus.OK);
    }

    @Log("新增商品")
    @ApiOperation(value = "新增商品")
    @CacheEvict(cacheNames = ShopConstants.PUSHMALL_REDIS_INDEX_KEY, allEntries = true)
    @PostMapping(value = "/PmStoreProduct")
    @PreAuthorize("@el.check('admin','YXSTOREPRODUCT_ALL','YXSTOREPRODUCT_CREATE')")
    public ResponseEntity create(@Validated @RequestBody PushMallStoreProduct resources) {
        //if(StrUtil.isNotEmpty("22")) throw new BadRequestException("演示环境禁止操作");
        int id = (int) (Math.random() * (352324 + 1));
        if (ObjectUtil.isNull(resources.getId())) {
            resources.setId(id);
        }
        resources.setAddTime(OrderUtil.getSecondTimestampTwo());
        if (ObjectUtil.isEmpty(resources.getGiveIntegral())) {
            resources.setGiveIntegral(BigDecimal.ZERO);
        }
        if (ObjectUtil.isEmpty(resources.getCost())) {
            resources.setCost(BigDecimal.ZERO);
        }
        return new ResponseEntity(pushMallStoreProductService.create(resources), HttpStatus.CREATED);
    }

    @Log("修改商品")
    @ApiOperation(value = "修改商品")
    @CacheEvict(cacheNames = ShopConstants.PUSHMALL_REDIS_INDEX_KEY, allEntries = true)
    @PutMapping(value = "/PmStoreProduct")
    @PreAuthorize("@el.check('admin','YXSTOREPRODUCT_ALL','YXSTOREPRODUCT_EDIT')")
    public ResponseEntity update(@Validated @RequestBody PushMallStoreProduct resources) {
        //if(StrUtil.isNotEmpty("22")) throw new BadRequestException("演示环境禁止操作");
        pushMallStoreProductService.update(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @Log("删除商品")
    @ApiOperation(value = "删除商品")
    @CacheEvict(cacheNames = ShopConstants.PUSHMALL_REDIS_INDEX_KEY, allEntries = true)
    @DeleteMapping(value = "/PmStoreProduct/{id}")
    @PreAuthorize("@el.check('admin','YXSTOREPRODUCT_ALL','YXSTOREPRODUCT_DELETE')")
    public ResponseEntity delete(@PathVariable Integer id) {
        //if(StrUtil.isNotEmpty("22")) throw new BadRequestException("演示环境禁止操作");
        pushMallStoreProductService.delete(id);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "恢复数据")
    @CacheEvict(cacheNames = ShopConstants.PUSHMALL_REDIS_INDEX_KEY, allEntries = true)
    @DeleteMapping(value = "/PmStoreProduct/recovery/{id}")
    @PreAuthorize("@el.check('admin','YXSTOREPRODUCT_ALL','YXSTOREPRODUCT_DELETE')")
    public ResponseEntity recovery(@PathVariable Integer id) {
        pushMallStoreProductService.recovery(id);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "商品上架/下架")
    @CacheEvict(cacheNames = ShopConstants.PUSHMALL_REDIS_INDEX_KEY, allEntries = true)
    @PostMapping(value = "/PmStoreProduct/onsale/{id}")
    public ResponseEntity onSale(@PathVariable Integer id, @RequestBody String jsonStr) {
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        int status = Integer.valueOf(jsonObject.get("status").toString());
        pushMallStoreProductService.onSale(id, status);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "生成属性")
    @PostMapping(value = "/PmStoreProduct/isFormatAttr/{id}")
    public ResponseEntity isFormatAttr(@PathVariable Integer id, @RequestBody String jsonStr) {
        return new ResponseEntity(pushMallStoreProductService.isFormatAttr(id, jsonStr), HttpStatus.OK);
    }

    @ApiOperation(value = "设置保存属性")
    @CacheEvict(cacheNames = ShopConstants.PUSHMALL_REDIS_INDEX_KEY, allEntries = true)
    @PostMapping(value = "/PmStoreProduct/setAttr/{id}")
    public ResponseEntity setAttr(@PathVariable Integer id, @RequestBody String jsonStr) {
        pushMallStoreProductService.createProductAttr(id, jsonStr);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "清除属性")
    @CacheEvict(cacheNames = ShopConstants.PUSHMALL_REDIS_INDEX_KEY, allEntries = true)
    @PostMapping(value = "/PmStoreProduct/clearAttr/{id}")
    public ResponseEntity clearAttr(@PathVariable Integer id) {
        pushMallStoreProductService.clearProductAttr(id, true);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "获取属性")
    @GetMapping(value = "/PmStoreProduct/attr/{id}")
    public ResponseEntity attr(@PathVariable Integer id) {
        String str = pushMallStoreProductService.getStoreProductAttrResult(id);
        if (StrUtil.isEmpty(str)) {
            return new ResponseEntity(HttpStatus.OK);
        }
        JSONObject jsonObject = JSON.parseObject(str);

        return new ResponseEntity(jsonObject, HttpStatus.OK);
    }

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/PmStoreProduct/download")
    @PreAuthorize("@el.check('admin','yxStoreProduct:list')")
    public void download(HttpServletResponse response,
                         PushMallStoreProductQueryCriteria criteria,
                         Pageable pageable,
                         @RequestParam(name = "listContent") String listContent) throws IOException, ParseException {
        List<PushMallStoreProductDTO> list = (List) getPushMallStoreProductList(criteria, pageable).get("content");
        List<PushMallStoreProductDTO> productList = new ArrayList<>();
        if (StringUtils.isEmpty(listContent)) {
            pushMallStoreProductService.download(list, response);
        } else if (listContent.equals("template")) {
            pushMallStoreProductService.download(productList, response);
        } else {
            List<String> idList = JSONArray.parseArray(listContent).toJavaList(String.class);
            productList = pushMallStoreProductService.findByIds(idList);

            pushMallStoreProductService.download(productList, response);
        }
    }

    @Log("上传商品信息")
    @ApiOperation("上传商品信息")
    @PostMapping(value = "/PmStoreProduct/upload")
    @PreAuthorize("@el.check('storage:add')")
    public ResponseEntity upload(@RequestParam("file") MultipartFile file) throws IOException, InvalidFormatException {
        String name = file.getOriginalFilename();
        return new ResponseEntity(pushMallStoreProductService.excelToList(file.getInputStream()), HttpStatus.CREATED);
    }


}
